﻿#include "recognize.h"
#include "oeasycommon.h"
#include <QDir>
#include <QFile>
#include <QHostAddress>
#include <QJsonObject>
#include <QJsonDocument>

Recognize::Recognize(QString id, STRUCT_RECOG_INFO &cfg, QObject *parent) :
    QObject(parent),
    m_state(true),
    m_id(id),
    m_cfg(cfg),
    m_jpg(),
    m_start(0),
    m_sock(),
    m_recogManager(Q_NULLPTR),
    m_reply(Q_NULLPTR),
    m_replyTimeout(Q_NULLPTR)
{
    connect(&m_sock, SIGNAL(readyRead()), this, SLOT(onDetectOver()));

    if (m_cfg.filter)
    {
        m_sock.connectToHost(QHostAddress::LocalHost, m_cfg.filterPort);
    }
}

Recognize::~Recognize()
{
    m_sock.disconnect();
    m_sock.close();
    if (m_replyTimeout != Q_NULLPTR)
    {
        m_replyTimeout->deleteLater();
    }
    if (m_reply != Q_NULLPTR)
    {
        m_reply->deleteLater();
    }
    if (m_recogManager != Q_NULLPTR)
    {
        m_recogManager->deleteLater();
    }
}

void Recognize::recognize(QByteArray jpg)
{
    if (!m_state)
    {
        //WARNING_PRINT << "still in recognize";
        return ;
    }

    m_state = false;
    m_start = clock();
    m_jpg = jpg;

    if (m_cfg.filter)
    {
        if (m_sock.state() == QAbstractSocket::ConnectedState && m_sock.isWritable())
        {
            m_sock.write(m_jpg.toBase64()+",");
        }
        else if (m_sock.state() == QAbstractSocket::UnconnectedState)
        {
            WARNING_PRINT << "filter process is in UnconnectedState";
            m_sock.connectToHost(QHostAddress::LocalHost, m_cfg.filterPort);
            m_state = true;
        }
        else
        {
            WARNING_PRINT << "filter process state is" << m_sock.state();
            m_state = true;
        }
    }
    else
    {
        comparison();
    }
}

void Recognize::comparison()
{
    QNetworkRequest req(QUrl(m_cfg.url + "?id=" + m_id));

    req.setHeader(QNetworkRequest::ContentTypeHeader, "image/jpeg");
    m_recogManager = new QNetworkAccessManager;
    connect(m_recogManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRecogFinished(QNetworkReply*)));
    m_reply = m_recogManager->post(req, m_jpg);
    if (m_reply != Q_NULLPTR && m_reply->isRunning())
    {
        m_replyTimeout = new QReplyTimeout(m_reply, 5000);
    }
}

void Recognize::saveFilterJpg(QString dir, QByteArray jpg)
{
    QDir *pDir = new QDir;
    if (!pDir->exists("filter_jpg"))
    {
        pDir->mkdir("filter_jpg");
    }
    if (!pDir->exists(QString("filter_jpg/%1").arg(dir)))
    {
        pDir->mkdir(QString("filter_jpg/%1").arg(dir));
    }
    delete pDir;

    QFile file(QString("filter_jpg/%1/%2.jpg").arg(dir, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")));
    if (file.open(QIODevice::WriteOnly))
    {
        file.write(jpg);
        file.close();
    }
}

void Recognize::onDetectOver()
{
    QByteArray result = m_sock.readAll();

    if (result.size() >= 1 && result.at(0) == '0')
    {
        // DEBUG_PRINT << m_id << "end" << clock() - m_start;
        if (m_cfg.saveFilterJpg)
        {
            this->saveFilterJpg(m_id, m_jpg);
        }
        m_state = true;
    }
    else if (result.size() >= 1 && result.at(0) == '1')
    {
        comparison();
    }
    else
    {
        WARNING_PRINT << m_id << "end" << clock() - m_start << result;
        m_state = true;
    }
}

void Recognize::onRecogFinished(QNetworkReply *)
{
    if (m_reply->error() != QNetworkReply::NoError)
    {
        WARNING_PRINT << m_reply->url() << m_reply->errorString();
    }
    else if (m_reply->isReadable())
    {
        QByteArray data = m_reply->readAll();

        DEBUG_PRINT << clock() - m_start << data;
        emit this->postOver(m_jpg, data);
    }

    if (m_replyTimeout != Q_NULLPTR)
    {
        m_replyTimeout->deleteLater();
        m_replyTimeout = Q_NULLPTR;
    }
    m_reply->deleteLater();
    m_reply = Q_NULLPTR;
    m_recogManager->deleteLater();
    m_recogManager = Q_NULLPTR;
    m_state = true;
}
